$(function() {
	// dynamic load of js file
	// $.ajax({
	// type: "GET",
	// url: "/mvc-ajax/scripts/json.min.js",
	// dataType: "script"
	// });
	// check name availability on focus lost
	$('#name').blur(function() {
		if ($('#name').val()) {
			checkAvailability();
		}
	});
	$("#account").submit(function() {
		var account = $(this).serializeObject();
		$.postJSON("account", account, function(data) {
			$("#assignedId").val(data.id);
			showPopup();
		});
		return false;
	});
	// toggling class
	$('#changeColor').click(function(event) {
		$(this).toggleClass('blue');
	});
	// hiding/showing
	$('#hide').toggle(function() {
		$('#toHide').hide();
	}, function() {
		$('#toHide').show();
	});

	// scroll
	// $.scrollTo('#toScroll');

	// hasClass
	// if($('*').hasClass('container')){
	// alert('true');
	// }
	// html()
	// alert($('.container').html('loh'));

	// attribute selector
	$('[for|=name]').css('color', 'red');

	// next element
	$('#changeColor + *').css('border', '2px red solid');

	// button selector
	// $(':button').append(' this is button');

	// all selector+prepend
	// $('*',$('ul')).hide();
	// var a = $('<h1>'+$('*').css('border','2px red solid').length+' elements
	// found </h1>');
	// var b= $('body');
	// var c=$('#changeColor');
	// a.appendTo(c);
	// b.prepend(a);

	// onclick event - additional data
	$('#forClick').bind('click', {
		msg : 'additional data'
	}, function(event) {
		alert(event.data.msg);
	});
	$('#forHide').click(function() {
		$(this).hide(100);
	});
	// fadding
	// $('#forFadeIn').toggle(
	// function(){
	// $('#fadded').fadeIn("slow");
	// },
	// function(){
	// $('#fadded').fadeOut("slow");
	// }
	// );
	// sliding
	$('#forFadeIn').click(function() {
		$('#fadded').slideToggle("slow");
	});

	// text()
	// alert($('div').text());

	// jsonp load all accounts
	$.ajax( {
		url : "http://localhost:8080/mvc-ajax/account/jsonp/allAcounts",
		dataType : "jsonp",
		type : 'GET',
		jsonp : 'jsonp',
		jsonpCallback : 'getAccounts',
		success : function(data) {
			$.each(data, function(key, value) {
				$('<h3><a href="#">' + value.name + '</a></h3>').appendTo(
						"#accordion");
				var container = $('<div></div>');
				$('<div>' +'money '+ value.balance + '</div>')
						.appendTo(container);
				$('<div>' +'location ' + value.location + '</div>')
				.appendTo(container);
				$('<div>' + value.renewalDate + '</div>')
				.appendTo(container);
				$('#accordion').append(container);
			});
			// JQUERY UI
			
			// accordion
			$("#accordion").accordion({
				fillSpace: true,
				collapsible: true
			});
			$( "#accordionResizer" ).resizable({
				minHeight: 140,
				resize: function() {
					$( "#accordion" ).accordion( "resize" );
				}
			});
		},
		error : function(XMLHttpRequest, textStatus, errorThrown) {
			alert(textStatus);
			alert(errorThrown);
		}
	});
	
	// JQUERY UI
	// datepicker
	$( "#datepicker" ).datepicker({ 
		dateFormat: 'dd.mm.yy' ,
		showOtherMonths: true,
		selectOtherMonths: true,
		showWeek: true,
		firstDay: 1,
//		showButtonPanel: true
		changeMonth: true,
		changeYear: true,
		showAnim: "bounce"
	});

	// autocomplete
	
	$( "#city" ).autocomplete({
		source: function( request, response ) {
			$.ajax({
				url: "http://ws.geonames.org/searchJSON",
				dataType: "jsonp",
				data: {
					featureClass: "P",
					style: "full",
					maxRows: 12,
					name_startsWith: request.term
				},
				success: function( data ) {
					response( $.map( data.geonames, function( item ) {
						return {
							label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
							value: item.name
						}
					}));
				}
			});
		},
		minLength: 2,
//		select: function( event, ui ) {
//			log( ui.item ?
//				"Selected: " + ui.item.label :
//				"Nothing selected, input was " + this.value);
//		},
		open: function() {
			$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
		},
		close: function() {
			$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
		}
	});
	
	// Button
	$( "button, input:submit" ).button();

});

function checkAvailability() {
	$.getJSON("account/availability", {
		name : $('#name').val()
	}, function(availability) {
		if (availability.available) {
			fieldValidated("name", {
				valid : true
			});
		} else {
			fieldValidated("name", {
				valid : false,
				message : $('#name').val() + " is not available, try "
						+ availability.suggestions
			});
		}
	});
}

function fieldValidated(field, result) {
	if (result.valid) {
		$("#" + field + "Label").removeClass("error");
		$("#" + field + "\\.errors").remove();
		$('#create').attr("disabled", false);
	} else {
		$("#" + field + "Label").addClass("error");
		if ($("#" + field + "\\.errors").length == 0) {
			$("#" + field).after(
					"<span id='" + field + ".errors'>" + result.message
							+ "</span>");
		} else {
			$("#" + field + "\\.errors").html(
					"<span id='" + field + ".errors'>" + result.message
							+ "</span>");
		}
		$('#create').attr("disabled", true);
	}
}

function showPopup() {
	$.getJSON("account/" + $("#assignedId").val(), function(account) {
		$("#confirmedName").val(account.name);
		$("#confirmedBalance").val(account.balance);
		$("#confirmedEquityAllocation").val(account.equityAllocation);
		$("#confirmedRenewalDate").val(account.renewalDate);
	});
	$('body').css('overflow', 'hidden');
	$('#popup').fadeIn('fast');
	$('#mask').fadeIn('fast');
}

function closePopup() {
	$('#popup').fadeOut('fast');
	$('#mask').fadeOut('fast');
	$('body').css('overflow', 'auto');
	resetForm();
}

function resetForm() {
	$('#account')[0].reset();
}